package com.th.therp.utils;

import com.th.therp.exception.BaseException;
import com.th.therp.mapper.UserMapper;
import com.th.therp.pojo.dto.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.regex.Pattern;

@Component
public class RegValidUtils {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    // 手机号校验正则
    private static final String PHONE_REGEX = "^1[3-9]\\d{9}$";
    // 密码校验正则
    private static final String PASSWORD_REGEX = "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d@#$%^&*]{8,20}$";
    // 名称校验正则
    private static final String USERNAME_REGEX = "^[a-zA-Z_\u4e00-\u9fa5][a-zA-Z0-9_\u4e00-\u9fa5]{1,19}$";

    public boolean isValidPhone(String phone) {
        return phone != null && Pattern.matches(PHONE_REGEX, phone);
    }

    public boolean isValidPassword(String password) {
        return password != null && Pattern.matches(PASSWORD_REGEX, password);
    }

    public boolean isValidUsername(String username) {
        return username != null && Pattern.matches(USERNAME_REGEX, username);
    }

    public boolean isValid(UserDto userDto) {
        if (userDto == null) {
            throw new BaseException("注册信息不能为空");
        }
        // 校验手机号
        if (userDto.getPhone() == null || !isValidPhone(userDto.getPhone())) {
            throw new BaseException("手机号格式不正确");
        }
        // 校验用户名
        if (userDto.getUsername() == null || !isValidUsername(userDto.getUsername())) {
            throw new BaseException("用户名格式不正确");
        }
        // 校验密码
        if (userDto.getPassword() == null || !isValidPassword(userDto.getPassword())) {
            throw new BaseException("密码格式不正确");
        }
        if (!userDto.getPassword().equals(userDto.getConfirmPassword())) {
            throw new BaseException("两次输入密码不一致");
        }
        // 校验验证码
        String code = redisTemplate.opsForValue().get("code");
        if (code == null || !code.equals(userDto.getCode())) {
            throw new BaseException("授权码错误或已过期");
        }
        // 判断用户是否已存在
        if (userMapper.findByUsername(userDto.getUsername()) != null) {
            throw new BaseException("该用户名称已被使用");
        }
        if (userMapper.findByPhone(userDto) != null) {
            throw new BaseException("该手机号已被注册");
        }
        return true;
    }
}
